﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using Ue.Infrastructure.UI.SkinnedControls.PartAutoMappings;

namespace Ue.Infrastructure.UI.SkinnedControls
{
    [ControlValueProperty("Entity")]
    public abstract class SkinnedPart<T> : SkinnedControl
    {
        #region 构造、字段、事件

        private IPartAutoMapping entityAutoMapping;
        private T part;

        public SkinnedPart()
        {
            this.PreInitializeSkin += new EventHandler<SkinnedEventArgs>(PreInitializeSkinCallback);
            this.InitializeSkined += new EventHandler<SkinnedEventArgs>(InitializeSkinedCallback);
        }

        protected virtual void InitializeSkinedCallback(object sender, SkinnedEventArgs e)
        {
            if (this.entityAutoMapping != null)
            {
                this.entityAutoMapping.ToView(this.Entity);
            }
        }

        protected virtual void PreInitializeSkinCallback(object sender, SkinnedEventArgs e)
        {
            this.entityAutoMapping = this.RegisterMappings(PartAutoMappingFactory.BuildEntityAutoMapping(new MappingControlProvide(e.Skin)));
        }

        #endregion

        public virtual T Entity 
        {
            get
            {
                if (this.part == null)
                {
                    this.part = this.BuildNewEntity();
                }

                if (this.EntityAutoMapping != null && this.part!=null)
                {
                    this.EntityAutoMapping.ToPart(this.part);
                }

                return this.part;
            }
            set 
            { 
                this.part = value; 
            }
        }

        protected IPartAutoMapping EntityAutoMapping 
        {
            get { return this.entityAutoMapping; }
        }
        
        public abstract IPartAutoMapping RegisterMappings(IPartAutoMapping registerMappingBuilder);

        protected abstract T BuildNewEntity();
    }
}
